import {
    getAddressList,
    addAddress,
    updateAddress,
    deleteAddress,
    setDefaultAddress as apiSetDefault
} from '../services/api.js'

// 统一错误处理器
const handleApiError = (error, defaultMessage) => {
    console.error('API Error:', error)
    const message = error.response?.data?.message || defaultMessage
    return Promise.reject(new Error(message || '网络请求异常，请检查连接'))
}

// 经纬度校验函数
const validateCoordinate = (value, type) => {
    const num = Number(value)
    if (isNaN(num)) return false

    const ranges = {
        longitude: [-180, 180],
        latitude: [-90, 90]
    }
    const [min, max] = ranges[type] || []
    return num >= min && num <= max
}

// 数据清洗处理器
const sanitizeAddressData = (data) => {
    const sanitized = { ...data }

        // 处理坐标精度
        ['longitude', 'latitude'].forEach(field => {
        if (validateCoordinate(data[field], field)) {
            sanitized[field] = Number(data[field]).toFixed(6)
        } else {
            sanitized[field] = null
        }
    })

    // 处理默认地址标记
    sanitized.isDefault = Boolean(data.isDefault)
    return sanitized
}

// 获取地址列表
const fetchAddressList = async () => {
    try {
        const res = await getAddressList()
        return res.map(item => ({
            addressId: item.id,
            userName: item.userName,
            phoneNumber: item.phoneNumber,
            addressDetail: item.addressDetail,
            latitude: item.latitude,
            longitude: item.longitude,
            isDefault: item.isDefault // 直接使用接口返回的布尔值
        }))
    } catch (error) {
        console.error('地址加载失败:', error)
        return []
    }
}

// 添加地址
const addNewAddress = (addressData) => {
    const validLongitude = validateCoordinate(addressData.longitude, 'longitude')
    const validLatitude = validateCoordinate(addressData.latitude, 'latitude')

    if (!validLongitude || !validLatitude) {
        return Promise.reject(new Error('无效的地理坐标'))
    }

    const sanitizedData = sanitizeAddressData({
        ...addressData,
        longitude: String(addressData.longitude),
        latitude: String(addressData.latitude)
    })

    return addAddress(sanitizedData)
        .then(response => sanitizeAddressData(response.data))
        .catch(error => handleApiError(error, '地址添加失败'))
}

// 更新地址
const updateExistingAddress = (addressData) => {
    if (!addressData.addressid) {
        return Promise.reject(new Error('无效的地址ID'))
    }

    const sanitizedData = sanitizeAddressData({
        ...addressData,
        longitude: String(addressData.longitude),
        latitude: String(addressData.latitude)
    })

    return updateAddress(sanitizedData)
        .then(response => sanitizeAddressData(response.data))
        .catch(error => handleApiError(error, '地址更新失败'))
}

// 设置默认地址
const setDefaultAddress = (addressId) => {
    // 参数验证
    if (!Number.isSafeInteger(Number(addressId))) {
        return Promise.reject(new Error('无效的地址ID'))
    }

    return apiSetDefault(addressId)
        .then(response => {
            // 处理响应数据
            if (response.data?.success) {
                return {
                    success: true,
                    data: response.data
                }
            }
            throw new Error('设置默认地址失败')
        })
        .catch(error => handleApiError(error, '设置默认地址失败'))
}

// 更新删除方法（添加关联逻辑）
const removeAddress = (id) => {
    if (!Number.isSafeInteger(Number(id))) {
        return Promise.reject(new Error('无效的地址ID'))
    }

    return deleteAddress(id)
        .then(response => ({
            success: true,
            data: response.data
        }))
        .catch(error => handleApiError(error, '地址删除失败'))
}
export {
    fetchAddressList,
    addNewAddress,
    updateExistingAddress,
    removeAddress,
    setDefaultAddress,
}